<template>
  <view :class="badgeClass">
    <text v-if="dot" class="sr-only">状态指示</text>
    <text v-else-if="Number(value) > 0" :class="textClass">
      {{ displayValue }}
    </text>
    <text v-else-if="!dot && value" :class="textClass">
      {{ value }}
    </text>
    <slot v-else />
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue'

interface Props {
  // 徽章类型
  type?: 'default' | 'primary' | 'success' | 'warning' | 'error' | 'info'
  // 徽章值
  value?: number | string
  // 是否显示圆点
  dot?: boolean
  // 是否显示数字
  number?: boolean
  // 最大显示数字
  max?: number
  // 尺寸
  size?: 'small' | 'medium' | 'large'
  // 形状
  shape?: 'rounded' | 'pill' | 'square'
  // 自定义类名
  customClass?: string
}

const props = withDefaults(defineProps<Props>(), {
  type: 'default',
  value: 0,
  dot: false,
  number: false,
  max: 99,
  size: 'medium',
  shape: 'rounded',
  customClass: '',
})

// 计算显示值
const displayValue = computed(() => {
  if (!props.number || typeof props.value !== 'number') {
    return props.value
  }

  if (props.value <= props.max) {
    return props.value.toString()
  }

  return `${props.max}+`
})

// 徽章样式
const badgeClass = computed(() => {
  const baseClass = 'inline-flex items-center justify-center font-medium'

  const typeClasses = {
    default: 'bg-gray-500 text-white',
    primary: 'bg-novel-primary text-white',
    success: 'bg-green-500 text-white',
    warning: 'bg-yellow-500 text-white',
    error: 'bg-red-500 text-white',
    info: 'bg-blue-500 text-white',
  }

  const sizeClasses = {
    small: props.dot ? 'w-2 h-2' : 'px-2 py-0.5 text-xs',
    medium: props.dot ? 'w-2.5 h-2.5' : 'px-2.5 py-1 text-sm',
    large: props.dot ? 'w-3 h-3' : 'px-3 py-1.5 text-base',
  }

  const shapeClasses = {
    rounded: 'rounded-custom',
    pill: 'rounded-full',
    square: 'rounded-none',
  }

  return [
    baseClass,
    typeClasses[props.type],
    sizeClasses[props.size],
    shapeClasses[props.shape],
    props.customClass,
  ].filter(Boolean).join(' ')
})

// 文字样式
const textClass = computed(() => {
  if (props.dot) {
    return 'sr-only'
  }

  return ''
})
</script>

<style scoped>
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
</style>